package com.techysky.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.techysky.entity.Adapt;
import com.techysky.repository.AdaptRepository;
import com.techysky.service.AdaptService;

/**
 * @author nichao
 * @date 2017-7-18
 * @remark 业务实现类
 */
@Service("fitnessService")
public class AdaptServiceImpl implements AdaptService {

	private static final long serialVersionUID = 1L;
	@Autowired
	private  AdaptRepository adaptRepository;

	@Override
	public Map<String,Object> query(Adapt adapt) {
		Map<String,Object> result=new HashMap<>();
		adapt.setPage(adapt.getPage()!=null?adapt.getPage():0);
		adapt.setSize(adapt.getSize()!=null?adapt.getSize():8);
		Page<Adapt> resultList=this.adaptRepository.findAll(queryConditions(adapt),new PageRequest(adapt.getPage(),adapt.getSize()));
		result.put("rows", resultList.getContent());
		result.put("total", resultList.getTotalElements());
		return result;
	}

	/**
	 * 等值匹配条件
	 * @return
	 */
	public Specification<Adapt> queryConditions(final Adapt adapt){
		
		return (Root<Adapt> root,CriteriaQuery<?> query, CriteriaBuilder cb)->{
            List<Predicate> predicate = new ArrayList<>();
            if(adapt!=null) {
				if(adapt.getProjectId()!=null&&!"".equals(adapt.getProjectId())) {
					predicate.add(cb.equal(root.get("projectId"), adapt.getProjectId()));		
				}
				if(adapt.getName()!=null)
					predicate.add(cb.like(root.get("name"),"%"+adapt.getName()+"%"));			
            }
            Predicate[] pre = new Predicate[predicate.size()];
            return query.where(predicate.toArray(pre)).getRestriction();
		};
	}
	@Override
	public List<Adapt> findByDmCode(String dmCode) {
		return this.adaptRepository.findByDmCode(dmCode);
	}

	@Override
	public List<Adapt> findByNameLike(String name) {
		return this.adaptRepository.findByNameLike("%"+(StringUtils.isEmpty(name)?"":name)+"%");
	}
}
